package com.example.amazlinglistview.adapter;

import java.util.ArrayList;
import java.util.List;

import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.example.amazlinglistview.MainActivity;
import com.example.amazlinglistview.R;
import com.example.amazlinglistview.domain.Cars;
import com.example.amazlinglistview.domain.Constants;
import com.example.amazlinglistview.domain.DealerInfo;
import com.example.amazlinglistview.domain.Dealers;
import com.example.amazlinglistview.domain.SeriesInfo;
import com.example.amazlinglistview.domain.SubSeries;
import com.example.amazlinglistview.widget.AmazingAdapter;

public class MyAdapter extends AmazingAdapter implements
		OnCheckedChangeListener {
	private MainActivity mContext;
	private SeriesInfo mSeriesInfo;
	private Dealers mDealers;
	@SuppressWarnings("rawtypes")
	private List<Pair> mList = null;
	private List<Cars> mCarList = null;
	private List<DealerInfo> mDealersList = null;
	private LayoutInflater mInflater;
	public RadioGroup mRgTypes, mRgSort;
	public RadioButton mRbtn4S, mRbtnCompre, mRbtnDistance, mRbtnHot,
			mRbtnPrice;

	@SuppressWarnings("rawtypes")
	public MyAdapter(MainActivity context, SeriesInfo mSeriesInfo,
			Dealers mDealers) {
		this.mContext = context;
		this.mSeriesInfo = mSeriesInfo;
		this.mDealers = mDealers;

		mInflater = mContext.getLayoutInflater();

		View header = mInflater.inflate(R.layout.car_series_cars_header, null);
		List<View> headerList = new ArrayList<View>();
		headerList.add(header);
		mList = new ArrayList<Pair>();
		// mList.add(new Pair("header", headerList));// 先将header添加进去
		buildDatalist();
	}

	/** 构建数据列表 */
	private void buildDatalist() {
		buildCarsData();
		buildDealersData();

	}

	/** 构建车型信息列表 */
	private void buildCarsData() {
		mCarList = new ArrayList<Cars>();
		List<SubSeries> subSeriesList = mSeriesInfo.getSubSeries();
		for (int i = 0; i < subSeriesList.size(); i++) {
			SubSeries subSeries = subSeriesList.get(i);
			String seriesName = subSeries.getSeriesName();// 车系名，用作Pair的Key
			List<Cars> cars = subSeries.getCars();// 车型列表，用作Pair的Value
			mCarList.addAll(cars);
			Pair<String, List<Cars>> pair = new Pair<String, List<Cars>>(
					seriesName, cars);// 构建存放Cars的Pair
			mList.add(pair);
		}
	}

	/** 构建经销商信息列表 */
	private void buildDealersData() {
		mDealersList = mDealers.getDealerInfos();
		Pair<String, List<DealerInfo>> pair = new Pair<String, List<DealerInfo>>(
				"dealers", mDealersList);
		mList.add(pair);
	}

	@Override
	public int getCount() {
		// int count = 0;
		// for (int i = 0; i < mList.size(); i++) {
		// List second = (List) mList.get(i).second;
		// count += second.size();
		// }
		return mCarList.size() + mCarList.size() + 1;
	}

	@Override
	public Object getItem(int position) {
		Object result = null;
		if (position == 0) {

		} else if (position < mCarList.size() + 1) {
			return mCarList.get(position - 1);
		} else if (position >= mCarList.size()
				&& position < mCarList.size() + mDealersList.size() + 1) {
			return mDealersList.get(position - mCarList.size() - 1);
		}
		return result;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	protected void onNextPageRequested(int page) {

	}

	@Override
	protected void bindSectionHeader(View view, int position,
			boolean displaySectionHeader) {
		if (displaySectionHeader) {
			// Log.e(TAG, "pos = "+position);
			if (position < mCarList.size()) {
				View section = view.findViewById(R.id.section);// CarsItem的section
				TextView tvSection = (TextView) section
						.findViewById(R.id.tv_section_cars);
				tvSection
						.setText((String) getSections()[getSectionForPosition(position)]);
				section.setVisibility(View.VISIBLE);
			} else if (position >= mCarList.size()
					&& position < mCarList.size() + mDealersList.size()) {
				View dealersSection = view
						.findViewById(R.id.header_dealers_item);
				// dealersSection.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	public View getAmazingView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.car_series_item, null);
		}
		View headerView = convertView.findViewById(R.id.header_item);
		View carsView = convertView.findViewById(R.id.rl_layout_cars_item);
		View dealersView = convertView
				.findViewById(R.id.rl_layout_dealers_item);

		Object item = getItem(position);
		if (position == 0) {
			headerView.setVisibility(View.VISIBLE);
			carsView.setVisibility(View.GONE);
			dealersView.setVisibility(View.GONE);
		} else if (item instanceof Cars) {
			headerView.setVisibility(View.GONE);
			carsView.setVisibility(View.VISIBLE);
			dealersView.setVisibility(View.GONE);
			carsView.findViewById(R.id.section).setVisibility(View.GONE);
		} else if (item instanceof DealerInfo) {
			headerView.setVisibility(View.GONE);
			carsView.setVisibility(View.GONE);
			dealersView.setVisibility(View.VISIBLE);
			if (position == mCarList.size() + 1) {
				dealersView.findViewById(R.id.header_dealers_item)
						.setVisibility(View.VISIBLE);
				mRgTypes = (RadioGroup) dealersView
						.findViewById(R.id.rg_types_header);
				mRgSort = (RadioGroup) dealersView
						.findViewById(R.id.rg_sort_header);
				mRbtn4S = (RadioButton) dealersView.findViewById(
						R.id.header_dealers_item).findViewById(
						R.id.rb_4s_header);
				mRbtnCompre = (RadioButton) dealersView.findViewById(
						R.id.header_dealers_item).findViewById(
						R.id.rb_compre_header);
				mRbtnDistance = (RadioButton) dealersView.findViewById(
						R.id.header_dealers_item).findViewById(
						R.id.rb_distance_header);
				mRbtnHot = (RadioButton) dealersView.findViewById(
						R.id.header_dealers_item).findViewById(
						R.id.rb_hot_header);
				mRbtnPrice = (RadioButton) dealersView.findViewById(
						R.id.header_dealers_item).findViewById(
						R.id.rb_price_header);

				mRgTypes.setOnCheckedChangeListener(this);
				mRgSort.setOnCheckedChangeListener(this);

				setRbtnsState();
			} else {
				dealersView.findViewById(R.id.header_dealers_item)
						.setVisibility(View.GONE);
			}
		}

		return convertView;
	}

	@Override
	public void configurePinnedHeader(View header, int position, int alpha) {
		View headerSection = header.findViewById(R.id.section_cars);
		if (position == 0) {// 在HeaderView的位置，只显示HeaderView，不显示Item
			headerSection.setVisibility(View.GONE);
			if (mContext.mHeaderView.getVisibility() == View.VISIBLE) {
				mContext.mHeaderView.setVisibility(View.GONE);
			}
		} else if (position < mCarList.size() + 1) {
			TextView tvSection = (TextView) headerSection
					.findViewById(R.id.tv_section_cars);
			tvSection
					.setText((String) getSections()[getSectionForPosition(position)]);

			headerSection.setVisibility(View.VISIBLE);

			if (mContext.mHeaderView.getVisibility() == View.VISIBLE) {
				mContext.mHeaderView.setVisibility(View.GONE);
			}
		} else if (position >= mCarList.size() + 1
				&& position < mCarList.size() + mDealersList.size() + 1) {
			headerSection.setVisibility(View.GONE);
			if (mContext.mHeaderView.getVisibility() != View.VISIBLE) {
				mContext.mHeaderView.setVisibility(View.VISIBLE);
			}
		}

	}

	@Override
	public int getPositionForSection(int section) {
		if (section < 0)
			section = 0;
		if (section >= mList.size())
			section = mList.size() - 1;
		int c = 0;
		for (int i = 0; i < mList.size(); i++) {
			if (section == i) {
				return c + 1;// 由于多了一个HeaderView，所以在返回值的时候要+1
			}
			c += ((List) mList.get(i).second).size();
		}
		return 0;
	}

	@Override
	public int getSectionForPosition(int position) {
		int c = 0;
		for (int i = 0; i < mList.size(); i++) {
			// 同上，由于多了一个HeaderView，所以在计算的时候对应的值要+1
			if (position >= c + 1
					&& position < c + ((List) mList.get(i).second).size() + 1) {
				return i;
			}
			c += ((List) mList.get(i).second).size();
		}
		return -1;
	}

	@Override
	public Object[] getSections() {
		// 计算时要将DealerInfo的size排除出去，所以数组大小为mList.size() - 1
		String[] sections = new String[mList.size() - 1];
		for (int i = 0; i < mList.size() - 1; i++) {
			sections[i] = (String) mList.get(i).first;
		}
		return sections;
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.rb_4s_header:
			if (mContext.mDealersState != Constants.DEALER_STATE_4S) {
				mContext.mDealersState = Constants.DEALER_STATE_4S;
				mContext.mHandler.sendEmptyMessage(Constants.DEALER_STATE_4S);
			}
			break;
		case R.id.rb_compre_header:
			if (mContext.mDealersState != Constants.DEALER_STATE_COMPRE) {
				mContext.mDealersState = Constants.DEALER_STATE_COMPRE;
				mContext.mHandler.sendEmptyMessage(Constants.DEALER_STATE_COMPRE);
			}

			break;
		case R.id.rb_distance_header:
			if (mContext.mSortState != Constants.SORT_STATE_DISTANCE) {
				mContext.mSortState = Constants.SORT_STATE_DISTANCE;
				mContext.mHandler.sendEmptyMessage(Constants.SORT_STATE_DISTANCE);
			}
			break;
		case R.id.rb_hot_header:
			if (mContext.mSortState != Constants.SORT_STATE_HOT) {
				mContext.mSortState = Constants.SORT_STATE_HOT;
				mContext.mHandler.sendEmptyMessage(Constants.SORT_STATE_HOT);
			}

			break;
		case R.id.rb_price_header:
			if (mContext.mSortState != Constants.SORT_STATE_PRICE) {
				mContext.mSortState = Constants.SORT_STATE_PRICE;
				mContext.mHandler.sendEmptyMessage(Constants.SORT_STATE_PRICE);
			}
			break;
		}
		mContext.setRbtnsState();
	}

	public void setRbtnsState() {
		if (mContext.mDealersState == Constants.DEALER_STATE_4S) {
			mRbtn4S.setChecked(true);
		} else if (mContext.mDealersState == Constants.DEALER_STATE_COMPRE) {
			mRbtnCompre.setChecked(true);
		}

		if (mContext.mSortState == Constants.SORT_STATE_DISTANCE) {
			mRbtnDistance.setChecked(true);
		} else if (mContext.mSortState == Constants.SORT_STATE_HOT) {
			mRbtnHot.setChecked(true);
		} else if (mContext.mSortState == Constants.SORT_STATE_PRICE) {
			mRbtnPrice.setChecked(true);
		}

	}

}
